<?php

namespace Apps\News\Controllers\Admin;
use Apps\News\Models\NewsModel;
use App\Controllers\AdminBase;

class Category extends AdminBase
{
    protected $newsModel;
    public $cats;

    public function __construct()
    {
        $this->newsModel = new NewsModel();
        $this->cats = $this->newsModel->getCatTreeData();
    }

    public function index()
    {
        $list = [];
        if (IS_POST) {
            $list = $this->newsModel->getCatTreeData();
            $return = [
                'total' => count($list),
                'data' => $list,
            ];
            $this->_json(0, 'ok', $return);
        }
        $vdata = [];
        return view('news/catindex.html', $vdata);
    }

    public function add()
    {
        $pid = (int) $this->request->getGet('pid');
        $data = ['pid' => $pid];
        if (IS_POST) {
            $data = $this->request->getPost('data');
            $ret = $this->newsModel->cat_add($data);
            if ($ret['code'] == 0) {
                $this->addSystemLog('添加表[news]分类【#' . $data['name'] . '】'); // 记录日志
                $this->_json($ret['code'], $ret['msg'], $ret['data']);
            }
            $this->_json($ret['code'], $ret['msg'], $ret['data']);
        }
        $cats = $this->newsModel->getCatTreeData();
        $vdata = [
            'data' => $data,
            'cats' => $cats,
        ];
        return view('news/catadd.html', $vdata);
    }

    public function edit()
    {
        $id = (int) $this->request->getGet('id');
        $data = $this->newsModel->cat_get($id);
        if (IS_POST) {
            $data = $this->request->getPost('data');
            $ret = $this->newsModel->cat_edit($id, $data);
            if ($ret['code'] == 0) {
                $this->addSystemLog('修改表[news]分类【#' . $data['name'] . '】'); // 记录日志
            }
            $this->_json($ret['code'], $ret['msg'], $ret['data']);
        }
        $cats = $this->newsModel->getCatTreeData();
        $vdata = [
            'data' => $data,
            'cats' => $cats,
        ];
        return view('news/catadd.html', $vdata);
    }

    public function del()
    {
        $yes = $no = 0;
        if (IS_POST) {
            $ids = $this->request->getPost('ids');
            if ($ids && is_array($ids)) {
                foreach ($ids as $id) {
                    $rt = $this->newsModel->cat_del($id);
                    if ($rt['code'] == 0) {
                        $this->addSystemLog('删除分类:#' . $id);
                        $yes++;
                    } else {
                        $no++;
                    }
                }
            } else {
                $this->_json(1, '参数错误');
            }
            $this->_json(0,'操作结果 成功：' . $yes . ',失败' . $no);
        }
        $this->_json(1, isset($rt['msg']) ? $rt['msg'] : '操作失败');
    }
}
